$(document).ready(function () {
    // window.frames[0].postMessage('换一个msg', 'http://localhost');
    var iframe = document.getElementsByTagName("iframe")[0];
    if(!iframe){return;}
    var IFRAME_HEIGHT = 0;
    var isExited;
    var TRS_URL = iframe.src;
    var isLogin = false;

    //忘记密码模块
    var phoneKey = false, //电话是否符合要求
        pwdKey = false, //密码是否符合要求
        sendMsgUse = true; //发送按钮是否能用


    myAddEvent(function (e) {
        handleData(e.data);
        console.log(e.data);
    });

    function myAddEvent(callback) { //addEventListener兼容性写法
        if (window.attachEvent) {
            window.attachEvent("onmessage", function (e) {
                callback(e);
            });
        } else {
            window.addEventListener('message', function (e) {
                callback(e);
            }, false);
        }
    }

    function sendMsgToIframe(target, data) { //给iframe发送消息
        var msg = {
            target: target,
            data: data
        };
        if (window.ActiveXObject) {
            msg = toString(msg);
        }
        window.frames[0].postMessage(msg, TRS_URL);
    }

    //传递documentUrl
    setTimeout(function(){
        sendMsgToIframe('dUrl', window.location.href);
    },2000)


    /**
     * ie7兼容，对象转字符串
     * 
     * @param {any} data 
     * @returns 
     */
    function toString(data) {
        if (data.data) {
            return data.target + ',' + data.data;
        } else {
            return '' + data.target;
        }
    }
    /**
     * ie7兼容，字符串转对象
     * 
     * @param {any} str 
     * @returns 
     */
    function toObject(str) {
        var obj = {};
        var arr = str.split(',');
        if (arr.length == 1) {
            obj.target = arr[0];
            obj.data = undefined;
        } else {
            obj.target = arr[0];
            obj.data = arr[1];
        }
        return obj;
    }

    var firstReg = true,
        firstForget = true;

    function handleData(data) { //数据处理
        //初始化iframe高度
        if (!isNaN(data)) {
            IFRAME_HEIGHT = Number(data);
            iframe.height = IFRAME_HEIGHT;
            return;
        }
        if (window.ActiveXObject) {
            data = toObject(data);
        }
        if (data instanceof Object) {
            switch (data.target) {
                case 'height':
                    adjustHeight(Number(iframe.height), IFRAME_HEIGHT, Number(data.data));
                    break;
                case 'comPrt':
                    doComPrt(data.data);
                    break;
                case 'frtPwd':
                    doFrtPwd();
                    break;
                case 'errPrt':
                    doErrPrt(data.data);
                    console.log(data.data)
                    break;
                case 'isExited':
                    isExited = data.data;
                    break;
                case 'canIUseS':
                    doCanIUseS();
                    break;
                case 'frtPrt':
                    frtPrt(data.data);
                    break;
                case 'frtHide':
                    frtHide();
                    break;
                case 'regPwd':
                    regPwd();
                    break;
                case 'regBan':
                    regBan();
                    break;
                case 'regUse':
                    regUse();
                    break;
                case 'regBtnA':
                    regBtnA(data.data);
                    break;
                case 'regBtnB':
                    regBtnB(data.data);
                    break;
                case 'login':
                    isLogin = data.data;
                    break;
            }
        }

    }
    //调整高度函数
    function adjustHeight(currentHeight, originHeight, increaseHeight) {
        if (increaseHeight < 0 || currentHeight == originHeight) {
            iframe.height = currentHeight + increaseHeight;
            return;
        }
    }
    //提示框显示
    function doComPrt(txt) {
        $(".forget-pwd-bg").show();
        $(".com-prompt-box").show();
        $(".com-prompt-item").text(txt);
    }

    function doFrtPwd() {
        $(".forget-pwd-bg").show();
        $(".forget-pwd-box").show();
    }

    function doErrPrt(txt) {
        $(".reg-error-prompt").show();
        $(".reg-error-prompt p").text(txt);
        setTimeout(function () {
            $(".reg-error-prompt").hide();
        }, 2000);
    }

    function doCanIUseS() {
        removeBind("请稍后在试");
        $("#forgetCaptchaBtn").text("60秒后可点击发送");
        var countTime = 60;
        lateSend($("#forgetCaptchaBtn")); //延时发送
        function lateSend(target) {
            if (countTime == 0 || countTime < 0) {
                sendMsgUse == true;
                $("#forgetCaptchaBtn").removeAttr("class");
                target.text("点击获取短信验证码");
                canIUseClick();
                return;
            } else {
                countTime--;
                target.text(countTime + "秒后可点击发送");
            }
            setTimeout(function () {
                lateSend(target);
            }, 1000);
        }
    }

    function frtPrt(txt) {
        $(".forget-error-prompt").show()
        $(".forget-error-prompt p").text(txt);
        setTimeout(function () {
            $(".forget-error-prompt").hide();
        }, 2000);
    }

    function frtHide() {
        $(".forget-pwd-bg").hide();
        $(".forget-pwd-box").hide();
    }

    function regPwd() {
        $(".forget-pwd-bg").show();
        $(".reg-pwd-box").show();
    }

    function regBan() {
        $(".reg-prompt-txt").show();
        $(".reg-icons").text("该用户已存在！");
        setTimeout(function () {
            $(".reg-prompt-txt").hide();
        }, 2000);
        // 用户已存在，则获取验证码按钮禁止状态
        $("#regCaptchaBtn").css({
            'cursor': 'not-allowed'
        });
    }

    function regUse() {
        $("#regCaptchaBtn").css({
            'cursor': 'pointer'
        });
    }

    function regBtnA(txt) {
        $(".reg-error-prompt").show();
        $(".reg-error-prompt p").text(txt);
        setTimeout(function () {
            $(".reg-error-prompt").hide()
        }, 2000);
    }

    function regBtnB(txt) {
        $(".reg-error-prompt").show().css({
            'margin-top': -50,
            'line-height': 28
        });
        $(".reg-error-prompt p").text(txt);
        setTimeout(function () {
            $(".reg-error-prompt").hide()
        }, 4000);
    }


    // 改变字体
    //字体大小的改变
    $(".fontSize-max").click(function () {
        $(".nx-atls-lists p").css('font-size', 18);
        $(".fontSize-max").addClass('intro');
        $(".fontSize-middle").removeClass('intro');
        $(".fontSize-min").removeClass('intro');
    });

    $(".fontSize-middle").click(function () {
        $(".nx-atls-lists p").css('font-size', 14);
        $(".fontSize-middle").addClass('intro');
        $(".fontSize-max").removeClass('intro');
        $(".fontSize-min").removeClass('intro');
    });

    $(".fontSize-min").click(function () {
        $(".nx-atls-lists p").css('font-size', 12);
        $(".fontSize-min").addClass('intro');
        $(".fontSize-max").removeClass('intro');
        $(".fontSize-middle").removeClass('intro');

    });
    //改变字体背景颜色
    $(".atls-1").click(function () {

        $(".nx-atls-lists").css('background', '#cefeff');
    });

    $(".atls-2").click(function () {
        $(".nx-atls-lists").css('background', '#f8f8c3');
    });

    $(".atls-3").click(function () {
        $(".nx-atls-lists").css('background', '#ffc7ff');
    });

    $(".atls-4").click(function () {
        $(".nx-atls-lists").css('background', '#9bccfa');
    });


    function hideFun() {
        $(".forget-pwd-bg").hide();
        $(".forget-pwd-box").hide();
    }

    function isExit() {
        var data = {
            method: "checkUser",
            username: $.trim($("#forgetTel").val())
        };
        sendMsgToIframe('isExit', data);
        setTimeout(function () {});
        return isExited;
    }

    function canIUseClick() { //发送按钮是否能用
        if ($.trim($("#forgetPwds").val()) && sendMsgUse && phoneKey && pwdKey) {
            $("#forgetCaptchaBtn").removeAttr("class");
            $("#forgetCaptchaBtn").unbind();
            //请求事件绑定
            $("#forgetCaptchaBtn").click(function () {
                var isExited = isExit();
                if (isExited == 1) {
                    $(".forget-error-prompt").show()
                    $(".forget-error-prompt p").text("该用户不存在");
                    setTimeout(function () {
                        $(".forget-error-prompt").hide()
                    }, 2000);
                    return;
                } else if (isExited == 2) {
                    return;
                }
                var data = {
                    method: "getSmsCaptcha",
                    username: $.trim($("#forgetTel").val())
                }
                sendMsgToIframe('canIUse', data);
            })

        } else {
            removeBind();
        }
    }

    removeBind(); //事件绑定之后解绑
    function removeBind(text) { //移除发送请求事件绑定
        var alertText = text || "请完成上面要求";
        $("#forgetCaptchaBtn").unbind();
        $("#forgetCaptchaBtn").click(function () {
            $(".forget-error-prompt").show();
            $(".forget-error-prompt p").text(alertText);
            setTimeout(function () {
                $(".forget-error-prompt").hide()
            }, 2000);
        });
        //css样式
        $("#forgetCaptchaBtn").attr("class", "unUse-zjd");
    }

    /*
     *@function 警告标签
     *@position 可传参数ph、pwd、pwds、val(验证码)
     *@text 警告文本
     */
    function fgtPrt(position, text) {
        var y = 60;
        switch (position) {
            case "val":
                y = 270;
                break;
            case "pwd":
                y = 130;
                break;
            case "pwds":
                y = 200;
                break;
            default:
                y = 60;
        }
        $(".forget-prompt-txt").show().css({
            'top': y
        });
        $(".forget-icons").text(text);
        setTimeout(function () {
            $(".forget-prompt-txt").hide()
        }, 2000);
    }

    /** 
     * 2018.3.13修改 统一事件绑定在document上 gov-3940
     */
    $(document).on('click', '.forget-pwd-bg', function () {
        hideFun();
    }).on('click', '#regCaptchaBtn', function () { // 获取手机验证码,注册
        var regTel = $("#regTel");
        data = {
            siteId: "EsiteId",
            method: "getSmsCaptcha",
            username: $.trim(regTel.val())
        };
        sendMsgToIframe('regCha', data);
    }).on('click', '#regPeopleLine', function () { // 网民注册
        var regName = $("#regTel");
        var regPwd = $("#regPwd");
        var regCaptcha = $("#regCaptcha");
        var registerPwdBase = $.base64.encode($.trim(regPwd.val()));
        if ($.trim(regName.val())) {
            if ($.trim(regPwd.val())) {
                if ($.trim(regCaptcha.val())) {
                    data = {
                        method: "register",
                        username: regName.val(),
                        password: registerPwdBase,
                        registerCaptcha: regCaptcha.val()
                    };
                    sendMsgToIframe('regBtn', data);
                } else {
                    $(".reg-prompt-txt").show().css({
                        'top': 200
                    });
                    $(".reg-icons").text("验证码不能为空！");
                    setTimeout(function () {
                        $(".reg-prompt-txt").hide()
                    }, 2000);
                }
            } else {
                $(".reg-prompt-txt").show().css({
                    'top': 130
                });
                $(".reg-icons").text("密码不能为空！");
                setTimeout(function () {
                    $(".reg-prompt-txt").hide()
                }, 2000);
            }
        } else {
            $(".reg-prompt-txt").show().css({
                'top': 60
            });
            $(".reg-icons").text("用户名不能为空！");
            setTimeout(function () {
                $(".reg-prompt-txt").hide()
            }, 2000);
        }
    }).on('click', '.forget-pwd-submitDynamic', function () { //忘记密码btn
        var tel = $.trim($("#forgetTel").val());
        var pwd = $.trim($("#forgetPwd").val());
        var pwds = $.trim($("#forgetPwds").val());
        var val = $.trim($("#forgetCaptcha").val());
        if (tel == "") {
            fgtPrt("ph", "请输入手机号码");
        } else if (!phoneKey) {
            fgtPrt("ph", "手机号码不正确");
        } else if (pwd == "") {
            fgtPrt("pwd", "请输入密码");
        } else if (pwd.length < 6 || pwd.length > 20) {
            fgtPrt("pwd", "密码长度在6-20位");
        } else if (pwds == "") {
            fgtPrt("pwds", "请输入确认密码");
        } else if (!pwdKey) {
            fgtPrt("pwds", "密码不一致");
        } else if (pwdKey && phoneKey) {
            if (val == "") {
                fgtPrt("val", "请输入验证码");
            } else if (val.length != 4) {
                fgtPrt("val", "验证码格式正确");
            } else {
                data = {
                    siteId: "EsiteId",
                    method: "resetPassword",
                    username: tel,
                    resetCaptcha: val,
                    newPasword: '__encoded__' + $.base64.encode(pwd),
                    repeatPassword: '__encoded__' + $.base64.encode(pwd)
                }
                sendMsgToIframe('frtSend', data);


            }
        }
    }).on('click', '.forget-pwd-bg', function () { // 公共弹框
        hideFun();
        $(this).hide();
        $(".com-prompt-box").hide();
        $(".reg-pwd-box").hide();
    }).on('click', '.com-prompt-btnlf', function () { // 提示信息（确定）
        $(".forget-pwd-bg").hide();
        $(".com-prompt-box").hide();
    }).on('click', '.com-prompt-btnft', function () { // 提示信息（关闭）
        $(".forget-pwd-bg").hide();
        $(".com-prompt-box").hide();
    }).on('click', '.forget-pwd-exit', function () { // 提示信息忘记密码（取消）
        $(".forget-pwd-bg").hide();
        $(".forget-pwd-box").hide();
    }).on('click', '.reg-pwd-exit', function () { // 提示信息注册（取消）
        $(".forget-pwd-bg").hide();
        $(".reg-pwd-box").hide();
    }).on('blur', '#regTel', function () { // 校验用户是否已经存在
        if (isLogin) return;
        if ($.trim($(this).val())) {
            if (!(/^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57]|199)[0-9]{8}$/.test($(this).val()))) {
                $(".reg-prompt-txt").show();
                $(".reg-icons").text("手机号码不正确！");
                setTimeout(function () {
                    $(".reg-prompt-txt").hide();
                }, 2000);
                return;
            }
            data = {
                method: 'checkUser',
                username: $.trim($(this).val())
            };
            sendMsgToIframe('regTel', data);
        }
    }).on('blur', '#forgetPwds', function () { //确认密码
        if (!$.trim($("#forgetPwd").val())) {
            pwdKey = false;
            removeBind();
            fgtPrt("pwd", "请输入密码");
        } else if ($.trim($("#forgetPwd").val()).length < 6 || $.trim($("#forgetPwd").val()).length > 20) {
            pwdKey = false;
            removeBind();
            fgtPrt("pwd", "密码长度在6-20位");
        } else if ($.trim($("#forgetPwds").val()) && ($.base64.encode($.trim($("#forgetPwd").val()))) != ($.base64.encode($.trim($("#forgetPwds").val())))) {
            pwdKey = false;
            removeBind();
            fgtPrt("pwds", "密码不一致");

        } else {
            pwdKey = true;
            canIUseClick();
        }
    }).on('blur', '#forgetPwd', function () { //新密码
        // $(".forget-prompt-txt").hide();
        if (!$.trim($("#forgetPwd").val())) {
            pwdKey = false;
            removeBind();
            fgtPrt("pwd", "请输入密码");
        } else if ($.trim($("#forgetPwd").val()).length < 6 || $.trim($("#forgetPwd").val()).length > 20) {
            pwdKey = false;
            removeBind();
            fgtPrt("pwd", "密码长度在6-20位");
        } else if ($.trim($("#forgetPwds").val()) && ($.base64.encode($.trim($("#forgetPwd").val()))) != ($.base64.encode($.trim($("#forgetPwds").val())))) {
            pwdKey = false;
            removeBind();
            fgtPrt("pwds", "密码不一致");
        } else if (!$.trim($("#forgetPwds").val())) {
            //不响应
        } else {
            pwdKey = true;
            canIUseClick();
        }
    }).on('blur', '#forgetTel', function () { //手机号码
        if ($.trim($(this).val())) {
            if (!(/^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57]|199)[0-9]{8}$/.test($(this).val()))) {
                phoneKey = false;
                removeBind();
                fgtPrt("ph", "手机号码不正确");
                return false;
            } else { //通过
                $(".forget-prompt-txt").hide();
                phoneKey = true;
                canIUseClick();
            }
        } else {
            phoneKey = false;
            removeBind();
            fgtPrt("ph", "请输入手机号码");
        }
    });
});

window.onload = function () {
    //弹出框append
    var regAndForStr = "<div class='reg-pwd-box' style='display: none;'><div class='reg-positon'><h3 class='reg-pwd-tit'>用户注册</h3><div class='reg-prompt-txt'><div class='reg-relat'><span class='reg-icons'>手机号码不能为空</span><i></i> </div></div><div class='reg-error-prompt'><p></p></div><input class='reg-input' id='regTel' type='text' placeholder='请输入手机号码'><input class='reg-input' id='regPwd' type='password' placeholder='请输入密码'><p class='reg-pwd-captcha clearfix'> <input type='text' id='regCaptcha' placeholder='验证码'> <a id='regCaptchaBtn' href='javascript:;'>点击获取短信验证码</a></p> <p class='reg-pwd-btns'><a id='regPeopleLine' class='forget-pwd-submit' href='javascript:;'>注册</a><a class='reg-pwd-exit' href='javascript:;'>取消</a> </p></div></div><div class='forget-pwd-box' style='display: none;height: 410px;'><div class='forget-positon'><h3 class='forget-pwd-tit'>重置密码</h3><div class='forget-prompt-txt'><div class='forget-relat'><span class='forget-icons'>手机号码不能为空</span><i></i></div></div><div class='forget-error-prompt'><p></p></div><input class='forget-input' id='forgetTel' type='text' placeholder='请输入注册时的手机号码'> <input class='forget-input' id='forgetPwd' type='password' placeholder='请输入新密码'><input class='forget-input' id='forgetPwds' type='password' placeholder='请确认密码'><p class='forget-pwd-captcha clearfix'><input type='text' id='forgetCaptcha' placeholder='验证码'><a id='forgetCaptchaBtn' href='javascript:;'>点击获取短信验证码</a></p><p class='forget-pwd-btns'> <a class='forget-pwd-submit forget-pwd-submitDynamic' href='javascript:;'>确定</a><a class='forget-pwd-exit' href=javascript:;>取消</a></p></div></div>";
    $("body").append(regAndForStr);
    var comPromptStr = "<div class='forget-pwd-bg'></div><div class='com-prompt-box'><div class='com-prompt-dw'><p class='com-prompt-tit'>信息提示</p><div class='com-prompt-lists'><p class='com-prompt-item'></p></div><div class='com-prompt-btns clearfix'><a class='com-prompt-btnlf' href='javascript:;'>确定</a><a class='com-prompt-btnft' href='javascript:;'>关闭</a></div></div></div>";
    $("body").append(comPromptStr);
    var forget_box_h = $(window).height();
    // $(".forget-pwd-bg").css({'height':forget_box_h,'display':'none'});
    $(window).resize(function () {
        var forget_box_h = $(window).height();
        $(".forget-pwd-bg").css({
            'height': forget_box_h
        });
    });
    /**
     * placeholder兼容ie9
     */
    var isPlaceholder = 'placeholder' in document.createElement('input'); //判断是否能用placeholder
    /**
     * 伪造placeholder样式
     * 
     */
    function createPlaceholder() {
        $('input').not("input[type='password']").each(function () {
            if ($(this).val() == "" && $(this).attr("placeholder") != "") {
                $(this).val($(this).attr("placeholder"));
                $(this).css('color', '#ccc');
                $(this).focus(function () {
                    if ($(this).val() == $(this).attr("placeholder")) {
                        $(this).val("");
                        $(this).css('color', '#000000');
                    }
                });
                $(this).blur(function () {
                    if ($(this).val() == "") {
                        $(this).val($(this).attr("placeholder"));
                        $(this).css('color', '#ccc');
                    }
                });
            }
        });

        //对password框的特殊处理1.创建一个text框 2获取焦点和失去焦点的时候切换
        $("input[type='password']").each(function () {
            var pwdField = $(this);
            var pwdVal = pwdField.attr('placeholder');
            pwdField.after('<input  class="reg-input forget-input" data-mark = "placeholder" type="text" value=' + pwdVal + ' autocomplete="off" />');
            var pwdPlaceholder = $(this).next('input');
            pwdPlaceholder.show();
            pwdPlaceholder.css('color', '#ccc');
            pwdField.hide();

            pwdPlaceholder.focus(function () {
                pwdPlaceholder.hide();
                pwdField.show();
                pwdField.focus();
            });

            pwdField.blur(function () {
                if (pwdField.val() == '') {
                    pwdPlaceholder.show();
                    pwdField.hide();
                }
            });
        });
    }
    if(!isPlaceholder)createPlaceholder();
};
